﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.Web.Http;
using Bootstrap_Project.Web.FixtureMaintenance;
using Bootstrap_Project.Web.Ports;
using System.Collections.ObjectModel;
using System.ServiceModel.Security;
using System.Globalization;
using System.Security.Principal;

namespace Bootstrap_Project.Web.Api_Services
{
    //--disable-web-security fix issue post request 404 error (only chrome)
    public class FixtureExtendController : ApiController
    {
        public static FixtureMaintenanceTCServiceClient fixClient 
        { 
            get 
            {
                FixtureMaintenanceTCServiceClient client = new FixtureMaintenanceTCServiceClient("InvoiceExportSecureEndpoint");
                client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
                WindowsImpersonationContext impersonationContext = ((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();
                impersonationContext.Undo();
                return client;
            }
        }
        //public static EmployeeServiceClient empClient { get; set; }
        public static PortServiceClient portClient
        {
            get
            {
               PortServiceClient  client = new PortServiceClient("portSecureEndpoint");
               client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
               return client;
            }
        }
        private static string SldDate;
        private static string VoyageStatus;

        static FixtureExtendController()
        {
            //empClient = new EmployeeServiceClient();
            //empClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
            SldDate = "All";
            VoyageStatus = "All";
        }
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public List<Account> Get(string name)
        {
            string xml = FixtureExtendController.fixClient.PerformOperation("findAccounts", string.Format("accountWellKnownName:{0}", name));
            Bootstrap_Project.Web.FixtureMaintenance.Reciept r = Serializer.Deserialize<Bootstrap_Project.Web.FixtureMaintenance.Reciept>(xml);
            List<Account> res = new List<Account>();
            if (r.Errors.Length == 0)
            {
                res = Serializer.Deserialize<List<Account>>(r.ResponsePayload);
                for (int i = 0; i < res.Count; i++)
                    if (!res[i].Name.ToLower().StartsWith(name.ToLower()))
                    {
                        res.RemoveAt(i);
                        i--;
                    }
            }
            return res;
        }


        //search fixtures
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public ObservableCollection<MaintenanceFixtureTC> Search(string Condition, string DateTo, string DateFrom, string DemurrageStatus,
            bool? IsActiveFixtures, bool? IsCurrentUserPrimary, bool? IsCurrentUserSecondary, string fixtureType)
        {
            IFormatProvider culture = new CultureInfo("en-US");
            string dateTo = new DateTime(2099, 1, 1).ToString(culture);
            string dateFrom = new DateTime(1970, 1, 1).ToString(culture);
            if (DateTo != null)
                dateTo = DateTime.ParseExact(DateTo, "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString(culture);
            if (DateFrom != null)
                dateFrom = DateTime.ParseExact(DateFrom, "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString(culture); 
            string xmlString = FixtureExtendController.fixClient.PerformOperation("find", 
                string.Format("SearchConditionForEFM:{0}&&dateTo:{1}&&dateFrom:{2}&&type:{3}&&onlyActive:{4}&&sldDate:{5}&&demurrageStatus:{6}&&voyageStatus:{7}&&currentUserOperatorPrimary:{8}&&currentUserOperatorSecondary:{9}",
                Condition, dateTo, dateFrom, fixtureType, IsActiveFixtures, FixtureExtendController.SldDate, DemurrageStatus,
                FixtureExtendController.VoyageStatus, IsCurrentUserPrimary, IsCurrentUserSecondary));
            Bootstrap_Project.Web.FixtureMaintenance.Reciept r = Serializer.Deserialize<Bootstrap_Project.Web.FixtureMaintenance.Reciept>(xmlString);
            ObservableCollection<MaintenanceFixtureTC> res = new ObservableCollection<MaintenanceFixtureTC>();
            if (r.Errors.Length == 0)
                res = Serializer.Deserialize<ObservableCollection<MaintenanceFixtureTC>>(r.ResponsePayload);
            return res;
        }

        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpPost]
        //close fixture
        public void  Post(ObservableCollection<MaintenanceFixtureTC> fixtures)
        {
            string str = FixtureExtendController.fixClient.PerformOperation("close", 
                string.Format("xmlSerializedObject:{0}", Serializer.Serialize<ObservableCollection<MaintenanceFixtureTC>>(fixtures)));
        }

    }
}
